<template>
    <a-spin :spinning="confirmLoading" style="background: #fff">
      <j-form-container :disabled="false">
        <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
          <a-collapse v-model="activeKey">
            <!-- 基本信息 -->
            <a-collapse-panel key="1" header="基本信息">
              <a-row :gutter="48">
                <!-- <a-col :span="8" :hidden="true">
                  <a-form-model-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle">
                    <a-input :disabled="formDisabled" v-model="model.nodeInfo.bpmBizTitle" placeholder="请输入标题"></a-input>
                  </a-form-model-item>
                </a-col> -->
                <!-- <a-col :span="8">
                  <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchaseBill">
                    <a-input v-model="model.purchaseBill" placeholder="请输入单据编号" disabled></a-input>
                  </a-form-model-item>
                </a-col> -->
                <a-col :span="8">
                  <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="handlerId">
                    <select-user-by-dep placeholder="请选择申请人" v-model="model.nodeInfo.handlerId" disabled />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="handlerDeptId">
                    <j-select-depart
                      placeholder="请选择申请部门"
                      v-model="model.nodeInfo.handlerDeptId"
                      disabled />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
                    <j-date
                      placeholder="请选择申请时间"
                      v-model="model.nodeInfo.createTime"
                      :show-time="true"
                      date-format="YYYY-MM-DD HH:mm:ss"
                      style="width: 100%"
                      disabled />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-collapse-panel>
            <!-- 物料明细 -->
            <a-collapse-panel key="2" header="项目信息">
              <a-row :gutter="48">
                <a-col :span="8">
                  <a-form-model-item label="项目名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectId">
                    <select-project-distribution-input
                      :disabled="formDisabled"
                      projectStatus="2"
                      :proDisabled="true"
                      :isContractManager="true"
                      v-model="model.project.id"
                      placeholder="请选择项目名称"
                    ></select-project-distribution-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="项目编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectBillNo">
                    <a-input disabled v-model="model.project.finalNo" placeholder="请输入项目编号"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="经营团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamName">
                    <select-team-input
                      disabled
                      v-model="model.project.teamName"
                      :tdlx="1"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-collapse-panel>
            <!-- 任务信息 -->
            <a-collapse-panel key="3" header="任务信息">
              <a-row :gutter="48">
                <a-col :span="8">
                  <a-form-model-item label="档案编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="taskBillNo">
                    <a-input disabled v-model="model.task.billNo" placeholder="请输入档案编号"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="业务分类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="categoryName">
                    <a-input disabled v-model="model.task.categoryName" placeholder="请输入业务分类"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="合同分配额(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractAmount">
                    <a-input-number
                      disabled
                      :max="99999999"
                      :min="0"
                      :precision="2"
                      v-model="model.task.contractAmount"
                      placeholder="请输入合同分配额"
                      style="width: 100%"/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="实施部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="executeDepart">
                    <j-select-depart :disabled="formDisabled" v-model="model.task.executeDepart" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item
                    label="项目负责人"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="projectLeading">
                    <select-user-by-dep v-model="model.task.projectLeading" :disabled="formDisabled"/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="24">
                  <a-form-model-item prop="taskFile" label="任务附件">
                    <j-upload v-if="!formDisabled" :disabled="formDisabled" v-model="model.task.taskFile"></j-upload>
                    <a-button v-else icon="download" @click="viewFile(model.task.taskFile)">文件列表</a-button>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-collapse-panel>
            <!-- 任务进度信息 -->
            <a-collapse-panel key="4" header="任务进度信息">
              <a-row :gutter="48">
                <a-col :span="24">
                  <a-table
                    ref="table"
                    size="middle"
                    rowKey="id"
                    bordered
                    :columns="columns"
                    :pagination="false"
                    :data-source="dataSource"
                    :loading="loading"
                  >
                    <span slot="nodeFile" slot-scope="text, record">
                      <a-button icon="download" @click="viewFile(record.nodeFile)">文件列表</a-button>
                    </span>
                  </a-table>
                </a-col>
              </a-row>
            </a-collapse-panel>
          </a-collapse>
        </a-form-model>
        <common-flow-list
          v-if="formBpm && model.bpmStatus !== '1'"
          :formData="formData"
          style="margin-top: 10px"></common-flow-list>
        <view-file-modal ref="viewFileModal"></view-file-modal>
      </j-form-container>
      <a-row :gutter="48">
        <a-col :span="24" style="text-align: center;margin-top: 15px">
          <a-button
            type="primary"
            v-if="formBpm"
            :style="{ marginRight: showFlowSubmitButton ? '10px' : '0px' }"
            @click="onPrint">打印</a-button>
          <a-button @click="submitForm('submit')" v-if="showFlowSubmitButton">提 交</a-button>
        </a-col>
      </a-row>
      <ErpProgressTaskNodeProcessFormPrint
        id="taskNodeProcessFormPrint"
        class="print_style"
        v-if="formBpm"
        :formData="model"
        :formDataHistory="formData"></ErpProgressTaskNodeProcessFormPrint>
    </a-spin>
  </template>
  
  <script>
  
  import { httpAction, getAction } from '@/api/manage'
  import { viewFile } from '@/utils/util'
  import ViewFileModal from '@/views/scy/components/ViewFileModal'
  import { mapGetters } from 'vuex';
  import moment from 'moment';
  import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
  import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
  import SelectProjectDistributionInput from '@/views/scy/components/SelectProjectDistributionInput'; //  项目名称
  import CommonFlowList from '@/views/components/CommonFlowList.vue';
  import Print from '@/utils/print/printarea.js';
  import { DragResizable } from '@/mixins/DragResizable'
  import ErpProgressTaskNodeProcessFormPrint from '@/views/erp/progress/modules/ErpProgressTaskNodeProcessFormPrint.vue';

  export default {
    name: 'taskProgressReportNodeProcessForm',
    mixins: [viewFile, DragResizable],
    components: {
      ViewFileModal,
      SelectTeamInput,
      SelectUserByDep,
      SelectProjectDistributionInput,
      CommonFlowList,
      ErpProgressTaskNodeProcessFormPrint
    },
    props: {
      // 流程表单data
      formData: {
        type: Object,
        default: () => { },
        required: false
      },
      // 表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    watch: {
      activeKey(key) {
        this.$forceUpdate()
      }
    },
    data() {
      return {
        modelExpectUseTime: null,
        activeKey: ['1', '2', '3', '4'],
        model: {
          nodeInfo: {},
          project: {},
          task: {}
        },
        labelCol: {},
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 }
        },
        confirmLoading: false,
        validatorRules: {
          'handlerId': [
            { required: true, message: '请选择申请人!', trigger: 'change' }
          ],
          projectId: [
            { required: true, message: '请选择项目名称!', trigger: 'change' }
          ]
        },
        loading: false,
        columns: [
          {
            title: '顺序',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '节点名称',
            align: 'center',
            dataIndex: 'nodeName',
            width: 180,
            ellipsis: true
          },
          {
            title: '节点进度(%)',
            align: 'center',
            dataIndex: 'nodeProgress',
            width: 100,
            ellipsis: true
          },
          {
            title: '消耗工时(天)',
            align: 'center',
            dataIndex: 'consumedHours',
            width: 100,
            ellipsis: true
          },
          {
            title: '完成时间',
            align: 'center',
            dataIndex: 'completeTime',
            width: 100,
            ellipsis: true
          },
          {
            title: '完成情况',
            align: 'center',
            dataIndex: 'completeDesc',
            width: 180,
            ellipsis: true
          },
          {
            title: '证明材料',
            align: 'center',
            dataIndex: 'nodeFile',
            width: 100,
            ellipsis: true,
            scopedSlots: { customRender: 'nodeFile' }
          }
        ],
        dataSource: [],
        url: {
          add: '/api/erp/purchase/procurement/erpPurchaseApplyForm/add',
          edit: '/api/erp/purchase/procurement/erpPurchaseApplyForm/edit',
          queryById: '/api/erp/progress/erpProgressTaskNode/getBpmInfoById',
          gainBillNo: '/api/erp/purchase/procurement/erpPurchaseApplyForm/gainBillNo',
          queryProvisionBroadList: '/api/erp/purchase/material/erpMaterialCategory/queryAllParent'
        },
        details: []
      }
    },
    computed: {
      formDisabled() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return true
          }
        }
        return false
      }
    },
    created() {
      // 备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      // 如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    methods: {
      ...mapGetters(['userInfo']),
      add() {
        this.edit(this.modelDefault);
        this.model.proposer = this.userInfo().empId; // 当前登录人
        this.model.proposerDeptId = this.userInfo().deptId; // 当前登录人部门
        this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss'); // 申请时间
        // this.model.applicant = this.userInfo().employee.orgDepart; //当前登录人单位
      },
      edit(record) {
        // this.$refs['form'].clearValidate()
        this.model = Object.assign({}, record)
        console.log('this.model', this.model)
        this.dataSource = record.nodeInfo ? [ record.nodeInfo ] : []
        this.visible = true;
      },
      // 渲染流程表单数据
      showFlowData() {
        if (this.formBpm === true) {
          let params = { id: this.formData.dataId };
          this.loading = true
          getAction(this.url.queryById, params).then((res) => {
            if (res.success) {
              console.log('res', res)
              this.edit(res.result);
            }
          }).finally(() => {
            this.loading = false
          })
        }
      },
      submitForm(type) {
        const that = this;
        if (type == 'draft') {
          // 代表保存草稿不做校验
          this.submit(type)
        } else if (type == 'submit') {
          let details = this.$refs.purchaseApply.submitForm()
          if (!details.length > 0) {
            this.$message.warning('请添加物料明细信息！');
            this.$emit('unButtonDisable');
            return
          }
  
          // 判断数据有没有填写数量或者预算价格
          var isAmount = details.some(item => !item.amount);
          var isBudgetAmount = details.some(item => item.budgetAmount === '' || item.budgetAmount === null);
          if (isAmount) {
            // 当为true说明有值领用数量没有填写
            this.$message.warning('请填写物料明细中的数量！');
            this.$emit('unButtonDisable');
            return false
          }
          if (isBudgetAmount) {
            // 当为true说明有值领用用途没有填写
            this.$message.warning('请填写物料明细中的预算价格！');
            this.$emit('unButtonDisable');
            return false
          }
          if (!(this.model.provisionBroad == '1535177497282371586') && this.model.isSupplier == 0 && this.model.purchaseBudgetAmount >= 10000) {
            this.$message.warning('当前采购总金额大于等于10000元，请走招标采购申请单！');
            this.$emit('unButtonDisable');
            return
          }
          // 触发表单验证
          this.$refs.form.validate(valid => {
            if (valid) {
              that.submit(type)
            } else {
              that.$emit('unButtonDisable')
            }
          })
        } else {
          console.log('传参数，保存：draft，提交：submit')
        }
      },
      submit(type) {
        const that = this;
        let details = this.$refs.purchaseApply.submitForm() || []
        that.confirmLoading = true;
        let httpurl = '';
        let method = '';
        if (!this.model.id) {
          httpurl += this.url.add;
          method = 'post';
        } else {
          httpurl += this.url.edit;
          method = 'put';
        }
        this.model.detailList = details
        this.model.expectUseTime = this.modelExpectUseTime
        httpAction(httpurl, this.model, method).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            if (method == 'post') {
              that.model.id = res.result;
            }
            that.$emit('ok', type, that.model);
          } else {
            that.$message.warning(res.message);
            that.$emit('unButtonDisable');
          }
        }).catch((error) => {
          that.$emit('unButtonDisable', error);
        }).finally(() => {
          that.confirmLoading = false;
        })
      },
  
      // 点击打印
      onPrint() {
        let print = new Print({
          el: '#taskNodeProcessFormPrint',
          popTitle: '任务进度详情 · 禾美环保',
          endCallback() {
  
          }
        })
      }
    }
  }
  </script>
  <style>
  /* @import "../../../../utils/print.css"; */
  
  .print_style {
    position: absolute;
    top: 0;
    z-index: -1111;
  }
  </style>
  